package com.baidu.controller;

import com.baidu.constant.MessageConstant;
import com.baidu.constant.QiNiuUtils;
import com.baidu.pojo.PageResult;
import com.baidu.pojo.QueryPageBean;
import com.baidu.pojo.Result;
import com.baidu.pojo.Setmeal;
import com.baidu.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@Controller
@ResponseBody
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        String filename = imgFile.getOriginalFilename();
        // 返回子字符串(".")在此字符串最右边出现的索引位置.
        int i = filename.lastIndexOf(".");
        // substring: 截取字符串, 从指定的位置开始
        // 为什么要截取图片后缀?? 因为图片格式很多种.
        String substring = filename.substring(i);

        // UUID 自动生成ID
        String uuid = UUID.randomUUID().toString() + substring;
        System.out.println("uuid:"+uuid);
        try {
            // uploadViaByte()
            QiNiuUtils.uploadViaByte(imgFile.getBytes(), uuid);

            // 返回上传成功的地址及图片名给前端
            Map<String, String> map = new HashMap<>();
            // 临时域名
            map.put("domain", QiNiuUtils.DOMAIN);
            // 服务器中图片的名称
            map.put("imageName", uuid);
            return new Result(true, MessageConstant.UPLOAD_SUCCESS, map);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.UPLOAD_SUCCESS);
        }
    }

    @PostMapping("/findAll")
    public Result findAll(@RequestBody QueryPageBean queryPageBean){
        System.out.println(queryPageBean);
        PageResult<Setmeal> pageResults = setmealService.findAll(queryPageBean);

        return new Result(true, MessageConstant.QUERY_CHECKGROUP_SUCCESS, pageResults);
    }

    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds){
        boolean b = setmealService.add(setmeal, checkgroupIds);
        if (b) {
            return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
        }
        return new Result(true, MessageConstant.ADD_SETMEAL_FAIL);
    }
}
